package com.jeffgalper.feather;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FeatherEntry {

   private String mFilename;
   private boolean mDirectory;
   private long mSize;

   public FeatherEntry(String filename, boolean directory, long size) {
      mFilename = filename;
      mDirectory = directory;
      mSize = size;
   }

   public FeatherEntry(InputStream mIn) throws IOException, FeatherException {
      DataInput input = new DataInputStream(mIn);
      checkMagicNumber(input);
      checkVersion(input);
      mFilename = getFilename(input);
      mDirectory = getDirectory(input);
      if (mDirectory)
         mSize = getSize(input);
   }

   private long getSize(DataInput input) throws IOException {
      return input.readLong();
   }

   private boolean getDirectory(DataInput input) throws IOException {
      byte flag = input.readByte();
      return flag == 1;
   }

   private String getFilename(DataInput input) throws IOException {
      short pathSize = input.readShort();
      return new String(readString(input, pathSize));
   }

   private void checkMagicNumber(DataInput in) throws IOException,
         FeatherException {
      String magic = new String(readString(in, Feather.MAGIC_FEATHER_STRING
            .length()));
      if (!Feather.MAGIC_FEATHER_STRING.equals(magic))
         throw new FeatherException("Not a valid Feather");
   }

   private void checkVersion(DataInput in) throws IOException, FeatherException {
      if (Feather.VERSION < in.readShort())
         throw new FeatherException("Incompatible version");
   }

   private String readString(DataInput in, int length) throws IOException {
      byte[] buf = new byte[length];
      in.readFully(buf);
      return new String(buf);
   }

   public String getFilename() {
      return mFilename;
   }

   public boolean isDirectory() {
      return mDirectory;
   }

   public long getSize() {
      return mSize;
   }
}
